﻿using System;
using log4net;
using System.IO;
using System.Text;
using System.Web;
using EasyMvc.Utility;

namespace EasyMvc.Web.Common
{
    public class Logger
    {
        #region Singleton
        private static Logger instance;
        private static object obj = new object();

        public static Logger Instance
        {
            get
            {
                lock (obj)
                {
                    if (instance == null)
                    {
                        log4net.Config.XmlConfigurator.Configure(new FileInfo(AppDomain.CurrentDomain.BaseDirectory + @"Config\log4net.xml"));
                        
                        instance = new Logger();
                    }
                }

                return instance;
            }
        }
        #endregion

        public void History(string action, object data)
        {
            var user = HttpContext.Current.User.Identity.Name;
            var datas = SerializationHelper.JsonSerialize(data, Encoding.UTF8);

            var sb = new StringBuilder();
            sb.AppendFormat("User: {0}\r\nAction: {1}\r\nData: {2}", user, action, datas);

            var history = LogManager.GetLogger("History");
            history.Info(sb.ToString());
        }

        public void Exception(Exception e)
        {
            var sb = new StringBuilder();
            sb.AppendFormat("Exception: {0}\r\nInnerException: {1}\r\n", e.Message, e.InnerException == null ? null : e.InnerException.Message);

            var exception = LogManager.GetLogger("Exception");
            exception.Error(sb.ToString());
        }
    }
}